<script setup name="login">
import { getCmsCode, getCmsLogin, getCmsRegister, getCmsRegisterCode, getServiceAgreement, getPrivacyAgreement, getUserInfo } from '@/axios/api/user'
import LfButton from '@/components/commonUI/LfButton.vue'
import LfDialog from '@/components/commonUI/LfDialog.vue'
import { useGlobalStore } from '@/stores/globalStore'
import { useChatStore } from '@/stores/chatStore'
import { setToken, setUserInfo } from '@/utils/webStorage'
import { ElMessage } from 'element-plus'
import { defineEmits } from 'vue'
import { useRoute,useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()


const globalStore = useGlobalStore()
const chatStore = useChatStore()

const mobile = ref('')
const code = ref('')
const agree = ref(false)
const loginOrRegister = ref('login')
const countdown = ref(0)
const showCode = ref('')
const showAgreementDialog = ref(false)
const agreementType = ref('')
const agreementContent = ref('')
const agreementTitle = ref('')
const adminUrl = ref(window.config_global.admin || 'http://localhost:5000')

const emit = defineEmits(['login-success'])

const handleLoginAdmin= () => {
  window.open(adminUrl.value, '_blank')
}

function closeModal() {
  globalStore.hideLogin()
}

const getSmsCode = () => {
  // 如果正在倒计时，直接返回
  if (countdown.value > 0) return

  // 校验手机号格式
  if (!mobile.value) {
    ElMessage({
      message: '请输入手机号',
      type: 'error',
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
    ElMessage({
      message: '手机号格式错误',
      type: 'error',
    })
    return
  }

  if (loginOrRegister.value === 'register' && !agree.value) {
    ElMessage({
      message: '请同意用户服务协议和隐私协议',
      type: 'error',
    })
    return
  }

  // 开始倒计时
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

  if (loginOrRegister.value === 'register') {
    getCmsRegisterCode({ mobile: mobile.value }).then((res) => {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      showCode.value = res.msg || '123456' // 假设返回的验证码在res.code中
    })
  } else {
    getCmsCode({ mobile: mobile.value }).then((res) => {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      showCode.value = res.msg || '123456' // 假设返回的验证码在res.code中
    })
  }
}

const login = () => {
  // 校验
  if (!mobile.value) {
    ElMessage({
      message: '请输入用户名',
      type: 'error',
    })
    return
  }

  if (!code.value) {
    ElMessage({
      message: '请输入密码',
      type: 'error',
    })
    return
  }

  // if (loginOrRegister.value === 'register' && !agree.value) {
  //   ElMessage({
  //     message: '请同意用户服务协议和隐私协议',
  //     type: 'error',
  //   })
  //   return
  // }

  if (loginOrRegister.value === 'login') {
    getCmsLogin({ username: mobile.value, password: code.value }).then((res) => {
      if (res.code === 200 || res.code === 0) {
        setToken(res.token)
        localStorage.setItem('ssotoken', res.ssotoken)
        // 获取用户信息并更新全局状态
        getUserInfo().then(userRes => {
          const userInfo = userRes.result
          setUserInfo(userInfo)
          // 更新全局状态
          chatStore.login(userInfo)
          // 获取好友列表
          chatStore.getFriendList()
          // 获取通知列表
          chatStore.getNoticeList()

          emit('login-success')
          ElMessage({
            message: '登录成功',
            type: 'success',
          })
          globalStore.hideLogin()

          if(route.query.token) {
            router.replace('/home')
          }
          setTimeout(()=>{
          // 刷新页面数据
           window.location.reload()
          },500)
        })
      } else {
        ElMessage({
          message: res.msg,
          type: 'error',
        })
      }
    })
  } else {
    getCmsRegister({ mobile: mobile.value, code: code.value }).then((res) => {
      if (res.code === 200 || res.code === 0) {
        setToken(res.token)
        // 获取用户信息并更新全局状态
        getUserInfo().then(userRes => {
          const userInfo = userRes.result
          setUserInfo(userInfo)
          // 更新全局状态
          chatStore.login(userInfo)
          // 获取好友列表
          chatStore.getFriendList()
          // 获取通知列表
          chatStore.getNoticeList()

          emit('login-success')
          ElMessage({
            message: '注册登录成功',
            type: 'success',
          })
          globalStore.hideLogin()



          // 刷新页面数据
          window.location.reload()
        })
      } else {
        ElMessage({
          message: res.msg,
          type: 'error',
        })
      }
    })
  }
}

const openAgreement = (type) => {
  agreementType.value = type
  agreementTitle.value = type === 'service' ? 'APP用户服务协议' : 'APP用户隐私协议'
  showAgreementDialog.value = true

  if (type === 'service') {
    getServiceAgreement().then(res => {
      agreementContent.value = res.result || '加载协议内容失败'
    }).catch(() => {
      agreementContent.value = '加载协议内容失败'
    })
  } else {
    getPrivacyAgreement().then(res => {
      agreementContent.value = res.result || '加载协议内容失败'
    }).catch(() => {
      agreementContent.value = '加载协议内容失败'
    })
  }
}

const closeAgreementDialog = () => {
  showAgreementDialog.value = false
  globalStore.showLoginDialog = true
}
</script>

<template>
  <LfDialog :isShow="globalStore.showLoginDialog" width="450px" height="400px" class="login-dialog">
    <div class="px-[50px] pt-[30px] pb-[10px]  flex flex-col h-full">
      <div>
        <!-- <div class="absolute right-6 top-6">
          <img src="/imgs/commonIcons/close.svg" alt="" class="cursor-pointer" @click="closeModal" />
        </div> -->
        <div class="text-[24px] text-center font-medium leading-6 text-[#16437C] mb-[50px]">
          <!-- {{ loginOrRegister === 'login' ? '登录' : '注册' }} -->
          登录
        </div>

        <div class="mt-2 flex flex-col gap-6">
          <div class="p-3 px-4 bg-[--fill-1] rounded-full">
            <input type="text" placeholder="输入用户名" v-model="mobile" class="bg-[--fill-1]" />
          </div>
          <div class="p-3 px-4 bg-[--fill-1] rounded-full flex justify-between">
            <input type="password" placeholder="输入密码" v-model="code" class="bg-[--fill-1]" />
            <!-- <div
              @click="getSmsCode"
              class="cursor-pointer"
              :class="{ 'text-gray-400 cursor-not-allowed': countdown > 0 }"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
            </div> -->
          </div>
          <!-- <div v-if="showCode" class="text-sm text-primary mt-1">
            {{ showCode }}
          </div> -->
        </div>

        <!-- <div v-if="loginOrRegister === 'register'" class="mt-4 text-sm text-gray-500 flex items-center gap-2">
          <input type="checkbox" v-model="agree" />
          <div>
            注册即代表同意<a class="text-primary" @click="openAgreement('service')">《APP用户服务协议》</a
            ><a class="text-primary" @click="openAgreement('privacy')">《APP用户隐私协议》</a>
          </div>
        </div> -->
      </div>
      <div class="mt-14">
        <LfButton type="primary" @click="login" size="full">
          <!-- {{
          loginOrRegister === 'login' ? '登录' : '注册并登录'
        }} -->
        登录
      </LfButton>
      <div  class="mt-4 text-sm  text-right text-[#2e5592]">
          <a class="text-[#2e5592]" @click="handleLoginAdmin('register')">管理后台登录</a>
        </div>
        <!-- <div v-if="loginOrRegister === 'login'" class="mt-4 text-sm text-gray-500">
          还没有账号？<a class="text-primary" @click="handleLoginOrRegister('register')">注册</a>
        </div>
        <div v-else class="mt-4 text-sm text-gray-500">
          已有账号？<a class="text-primary" @click="handleLoginOrRegister('login')">登录</a>
        </div> -->
      </div>
    </div>
  </LfDialog>
  <LfDialog :isShow="showAgreementDialog" @close="closeAgreementDialog" width="600px" height="auto" :append-to-body="true">
    <div class="px-6 py-4">
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-medium">{{ agreementTitle }}</h2>
        <img src="/imgs/commonIcons/close.svg" alt="" class="cursor-pointer" @click="closeAgreementDialog" />
      </div>
      <div class="max-h-[60vh] overflow-y-auto p-4 border rounded">
        <div v-html="agreementContent" class="agreement-content"></div>
      </div>
      <div class="mt-4 text-right">
        <LfButton @click="closeAgreementDialog">关闭</LfButton>
      </div>
    </div>
  </LfDialog>
</template>

<style lang="scss">

.login-dialog{
  >.fixed{
    background-color: #e3e3e7;
  }
}
</style>
